package com.cyt.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.BaseConstant;
import com.cyt.base.util.BaseUtil;
import com.cyt.base.util.DictCode;
import com.cyt.base.util.ErrorCode;
import com.cyt.sys.dao.SysRoleDao;
import com.cyt.sys.model.po.SysRole;
import com.cyt.sys.model.po.SysRoleMenu;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.model.vo.SysRoleVo;
import com.cyt.sys.service.SysRoleMenuService;
import com.cyt.sys.service.SysRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.StringUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 角色Service层实现类
 *
 * @author shengQiang yu
 * @date 2019-04-24 9:53
 */
@Service("baseRoleService")
public class SysRoleServiceImpl extends BaseServiceImpl<SysRole> implements SysRoleService {
    @Resource
    private SysRoleDao sysRoleDao;
    @Resource
    private SysRoleMenuService sysRoleMenuService;
    @Resource
    private SysRoleService sysRoleService;
    @Autowired
    public void setBaseDao(SysRoleDao sysRoleDao) {
        this.baseDao = sysRoleDao;
    }

    private SysRole sysRole;

    /**
     * 分页查询
     *
     * @param sysRoleVo 对象
     * @param pageSize 当前页面
     * @param pageNum 页面数量
     * @return ReturnResult 对象
     * @author shengQiang yu
     * @date 2018-11-29 15:43
     */
    public ReturnResult page(SysRoleVo sysRoleVo, int pageSize, int pageNum) {
        PageHelper.startPage(pageNum,pageSize);
        PageHelper.orderBy(" sort desc,create_time desc");
        List<SysRole> list=listExample(sysRoleVo);
        PageInfo<SysRole> page=new PageInfo<SysRole>(list);
        return new ReturnResult(page.getList(),page.getTotal(),page.isHasNextPage());
    }


    /**
     * 根据主键id集合软删除
     *
     * @param ids 主键id集合，多个以‘，’隔开
     * @param currentUser 当前用户
     * @return ReturnResult 对象
     * @author shengQiang yu
     * @date 2018-11-29 15:43
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult removeByIds(String ids,SysUser currentUser) {
        String[] idList=ids.split(",");
        boolean flage=true;
        for (String id:idList){
            SysRole sysRole = sysRoleDao.selectByPrimaryKey(id);
            sysRole.setRemoveTag(BaseConstant.REMOVE_TAG_YES);
            sysRole.setUpdateTime(new Date());
            sysRole.setUpdateUser(currentUser.getId());
            int num= sysRoleDao.updateByPrimaryKey(sysRole);
            if(num<0){
                flage=false;
            }
        }
        if(flage){
            return new ReturnResult();
        }else{
            return new ReturnResult(ErrorCode.CODE_1,ErrorCode.CODE_DELETE_FAIL_MSG);
        }
    }


    /**
     * 添加或修改
     *
     * @param sysRoleVo 对象
     * @param currentUser 当前用户
     * @return ReturnResult 对象
     * @author liufu zhu
     * @date 2018-11-29 15:43
     */
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(SysRoleVo sysRoleVo, SysUser currentUser) {
        if (checkRolePermission(sysRoleVo.getId(), sysRoleVo.getPermission())) {
            return new ReturnResult(ErrorCode.CODE_1, "该权限字符已使用");
        }
        //是否增加操作
        boolean isAdd=false;
        if (StrUtil.isEmpty(sysRoleVo.getId())) {
            isAdd=true;
            sysRole = new SysRole(currentUser);
        } else {
            sysRole = sysRoleDao.selectByPrimaryKey(sysRoleVo.getId());
            sysRole.setUpdateTime(new Date());
            sysRole.setUpdateUser(currentUser.getId());
        }
        sysRole.setRoleName(sysRoleVo.getRoleName());
        sysRole.setPermission(sysRoleVo.getPermission());
        sysRole.setStatus(sysRoleVo.getStatus());
        sysRole.setSort(sysRoleVo.getSort());
        if(isAdd){
            //增加操作
            int num = sysRoleDao.insert(sysRole);
            if (num <= 0) {
                return new ReturnResult(ErrorCode.CODE_1,ErrorCode.CODE_ADD_FAIL_MSG);
            }else {
                addBaseRoleMenu(sysRoleVo.getMenuIds(), sysRole.getId());
            }
        }else{
            //修改操作
            int num = sysRoleDao.updateByPrimaryKey(sysRole);
            if (num <= 0) {
                return new ReturnResult(ErrorCode.CODE_1,ErrorCode.CODE_UPDATE_FAIL_MSG);
            }else{
                sysRoleMenuService.deleteByRoleId(sysRole.getId());
                addBaseRoleMenu(sysRoleVo.getMenuIds(), sysRole.getId());
            }
        }
        return new ReturnResult(BaseConstant.DATABASE_SUCCEED_MSG);
    }

    private boolean checkRolePermission(String id, String permission) {
        SysRole t = new SysRole();
        t.setPermission(permission);
        t.setRemoveTag(DictCode.BASE_REMOVE_TAG_NORMAL);
        SysRole sysRole = sysRoleDao.selectOne(t);
        if (StringUtils.isBlank(id)) {
            return sysRole != null;
        } else {
            return sysRole != null && !sysRole.getId().equals(id);
        }
    }


    /**
     * 查询对象集合
     *
     * @param sysRoleVo 对象
     * @return List BaseRole对象集合
     * @author shengQiang yu
     * @date 2018-11-29 15:43
     */
    public List<SysRole> listExample(SysRoleVo sysRoleVo) {
        Example example = new Example(SysRole.class);
        Example.Criteria criteria = example.createCriteria();
        example.setOrderByClause(" sort desc");
        if (StringUtil.isNotEmpty(sysRoleVo.getRoleName())) {
            criteria.andLike("roleName", "%" + sysRoleVo.getRoleName() + "%");
        }
        if (StringUtil.isNotEmpty(sysRoleVo.getStatus())) {
            criteria.andEqualTo("status", sysRoleVo.getStatus());
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        return sysRoleDao.selectByExample(example);
    }

    /**
     * 获取角色树
     *
     * @param sysRoleVo 对象
     * @return ReturnResult 对象
     * @author shengQiang yu
     * @date 2018-11-29 15:43
     */
    @Override
    public ReturnResult dTreeList(SysRoleVo sysRoleVo) {
        List<SysRole> list = listExample(sysRoleVo);
        List<Map<String,Object>> dtreeEntityList=new ArrayList<Map<String,Object>>();
        for(SysRole sysRole :list){
            Map<String,Object> dtreeEntity=new HashedMap();
            dtreeEntity.put("id", sysRole.getId());
            dtreeEntity.put("title", sysRole.getRoleName());
            dtreeEntity.put("parentId","0");
            dtreeEntity.put("isLast",true);
            Map<String,String> m=new HashedMap();
            m.put("type","0");
            m.put("isChecked","0");
            List<Map<String,String>> dtreeCheckEntityList=new ArrayList<Map<String,String>>();
            dtreeCheckEntityList.add(m);
            dtreeEntity.put("checkArr",dtreeCheckEntityList);
            dtreeEntityList.add(dtreeEntity);
        }
        return new ReturnResult(dtreeEntityList);
    }


    /**
     * 获取角色名称集合
     *
     * @param roleIds 角色id集合
     * @return ReturnResult 对象
     * @author shengQiang yu
     * @date 2018-11-29 15:43
     */
    public String selectRoleNames(String roleIds){
        return sysRoleDao.selectRoleNames(roleIds);
    }

    /**
     *根据角色id获取角色和角色菜单集合
     *
     * @param roleId 角色id
     * @return
     * @author shengQiang yu
     * @date 2018-12-15 10:51
     */
    public SysRole selectRoleMenuByRoleId(String roleId){
        return sysRoleDao.selectRoleMenuByRoleId(roleId);
    }

    /**
     * 批量添加角色菜单
     *
     * @param menuIds 菜单集合
     * @param roleId 角色id
     * @author shengQiang yu
     * @date 2018-12-15 10:33
     */
    private void addBaseRoleMenu(String menuIds,String roleId){
        if(StringUtil.isNotEmpty(menuIds)){
            String[] menuIdList=menuIds.split(",");
            for (String menuId:menuIdList){
                SysRoleMenu sysRoleMenu =new SysRoleMenu();
                sysRoleMenu.setId(BaseUtil.uId());
                sysRoleMenu.setCreateTime(new Date());
                sysRoleMenu.setMenuId(menuId);
                sysRoleMenu.setRoleId(roleId);
                sysRoleMenuService.insert(sysRoleMenu);
            }
        }
    }

    /**
     * 根据reoleId查询用户
     *
     * @author changZheng hou
     * @date 2019/4/8 11:04
     */
   public List<String> selectUserIdByRoleId(String roleId){
       return sysRoleDao.selectUserIdByRoleId(roleId);
   }
}
